package com.huike.service.system.impl;

import com.huike.common.TreeSelect;
import com.huike.exception.MessageConstant;
import com.huike.exception.MessageException;
import com.huike.mapper.system.SysDeptMapper;
import com.huike.pojo.SysDept;
import com.huike.result.Result;
import com.huike.service.system.DeptSystemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptSystemServiceImpl implements DeptSystemService {
    @Autowired
    private SysDeptMapper deptMapper;


    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public void deleteDeptById(Long deptId) {
        Integer count = deptMapper.hasChildByDeptId(deptId);
        if (count > 0) {
            throw new MessageException(MessageConstant.DEPT_ERROR);
        }
        Integer count2 = deptMapper.checkDeptExistUser(deptId);
        if (count2 > 0) {
            throw new MessageException(MessageConstant.DEPT_MEN_ERROR);
        }
        deptMapper.deleteByDeptId(deptId);
    }

    @Override
    public List<SysDept> treeselect(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<SysDept> addDept(SysDept dept) {
        SysDept deptname = deptMapper.getByDeptname(dept.getDeptName());
        if (null == deptname) {
            throw new MessageException(MessageConstant.DEPTNAME_NOT_ONE);
        }
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(dept, sysDept);
        sysDept.setStatus(String.valueOf(MessageConstant.START_ONE));
        deptMapper.save(sysDept);
        return (List<SysDept>) Result.success();
    }


    private List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        return returnList;
    }
}
